import sys
import math
import random
from PyQt5.QtCore import Qt, QTimer, QRectF, QPointF
from PyQt5.QtGui import (QImage, QPainter, QPainterPath, QLinearGradient,
                         QColor, QTransform)
from PyQt5.QtWidgets import QApplication, QWidget

class AdvancedWaterEffect(QWidget):
    def __init__(self, img_path):
        super().__init__()
        self.original_img = QImage(img_path)
        self.wave_phase = 0.0
        self.params = {
            'amplitude': 12,        # 主波振幅
            'secondary_amp_ratio': 0.6, # 次级波振幅比例  
            'wave_freq': 0.18,      # 波浪密度
            'speed': 0.15,          # 移动速度
            'reflect_height': 0.7   # 倒影高度比例
        }
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("Java风格水波模拟")
        self.setFixedSize(self.original_img.width(), 
                         self.original_img.height() * 1.8)
        
        # 生成倒影并预处理
        self.reflection_img = self.original_img.mirrored(False, True)
        self.apply_reflection_mask()
        
        # 动画引擎
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.animate_wave)
        self.timer.start(33)  # 30fps

    def apply_reflection_mask(self):
        """应用倒影渐变蒙版"""
        grad = QLinearGradient(0, 0, 0, self.reflection_img.height())
        grad.setColorAt(0, QColor(255,255,255,200))
        grad.setColorAt(1, QColor(0,0,0,50))
        
        painter = QPainter(self.reflection_img)
        painter.setCompositionMode(QPainter.CompositionMode_Darken)
        painter.fillRect(self.reflection_img.rect(), grad)
        painter.end()

    def animate_wave(self):
        """更新波浪相位"""
        self.wave_phase += self.params['speed']
        self.wave_phase += random.uniform(-0.02, 0.02)  # 随机扰动
        self.update()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
        
        # 绘制原图
        painter.drawImage(0, 0, self.original_img)
        
        # 绘制倒影
        self.draw_reflection(painter)

    def draw_reflection(self, painter):
        """绘制动态水波倒影"""
        img_h = self.original_img.height()
        rect = QRectF(0, img_h, self.width(), img_h * self.params['reflect_height'])
        
        # 生成波纹路径
        wave_path = self.generate_wave_path(rect)
        
        # 波纹裁剪
        painter.save()
        painter.setClipPath(wave_path)
        
        # 添加折射扭曲
        if self.wave_phase % 6.28 > 3:  # 每半周期切换扭曲方向
            painter.setTransform(QTransform().translate(2, 0))
        else:
            painter.setTransform(QTransform().translate(-2, 0))
        
        painter.drawImage(rect, self.reflection_img)
        painter.restore()
        
        # 绘制高光
        self.draw_water_highlight(painter, rect)

    def generate_wave_path(self, rect):
        """生成复合波纹路径"""
        path = QPainterPath()
        path.moveTo(rect.left()-10, rect.top())
        
        A = self.params['amplitude']
        w = self.params['wave_freq']
        phase = self.wave_phase
        
        for x in range(int(rect.left()-10), int(rect.right()+10)):
            # 主波 + 次级波
            y1 = A * math.sin(w * x + phase)
            y2 = self.params['secondary_amp_ratio'] * A * math.cos(2*w*x + phase)
            y = y1 + y2
            
            path.lineTo(x, rect.top() + y)
        
        path.lineTo(rect.right()+10, rect.bottom())
        path.lineTo(rect.left()-10, rect.bottom())
        return path

    def draw_water_highlight(self, painter, rect):
        """绘制波峰高光"""
        # 第一层高光（主波）
        highlight1 = QLinearGradient(rect.topLeft(), rect.bottomLeft())
        highlight1.setColorAt(0.2, QColor(255,255,255,120))
        highlight1.setColorAt(0.5, Qt.transparent)
        
        # 第二层高光（次级波） 
        highlight2 = QLinearGradient(QPointF(-50, rect.top()), rect.bottomRight())
        highlight2.setColorAt(0.4, QColor(255,255,255,60))
        highlight2.setColorAt(0.8, Qt.transparent)
        
        painter.setPen(Qt.NoPen)
        painter.setBrush(highlight1)
        painter.drawRect(rect)
        painter.setBrush(highlight2)
        painter.drawRect(rect.adjusted(-20,0,20,0))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = AdvancedWaterEffect("../img/beauty02.png")
    window.show()
    sys.exit(app.exec_())